package com.example.huangliting.experimentalarrangementsystem.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.example.huangliting.experimentalarrangementsystem.R;
import com.example.huangliting.experimentalarrangementsystem.bean.Semester;
import com.example.huangliting.experimentalarrangementsystem.util.HttpUtils;
import com.example.huangliting.experimentalarrangementsystem.widget.ItemGroup;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class SetWeekActivity extends AppCompatActivity implements ItemGroup.ItemOnClickListener{

    /*final String setUrl = "http://10.0.2.2:8080/timetable/setConditions";
        final String findUrl = "http://10.0.2.2:8080/timetable/findConditions";*/
    final String setUrl = HttpUtils.headerUrl+"timetable/setConditions";
    final String findUrl = HttpUtils.headerUrl+"timetable/findSemesters";
    private static final String TAG = "ViewConditionsActivity";
    private int checkNum_semester = 0;
    private int checkNum_week = 0;
    private int checkNum = 0;
    private Context mContext;
    private ItemGroup semesterIG, weekIG;
    private Button backBtn;
    private Button submitBtn;
    private SharedPreferences sp;
    private String userName;
    private String[] semesterItems;
    private String[] weekItems;
    private String checkSemester;
    private List<Semester> semesters;
    public static final int SHOW_RESPONSE = 0;

    JSONArray semesterJson;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.set_week);
        mContext = this;
        Intent intent = getIntent();
        checkNum_week = intent.getIntExtra("thisWeekNum",0)-1;
        checkSemester = intent.getStringExtra("semester");
        initView();
        findSemestersByGET();
        /*返回操作*/
        backBtn = findViewById(R.id.toolbar_left_btn);
        backBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                Intent intent=new Intent();
                Bundle bundle=new Bundle();
                bundle.putString("weekid", semesters.get(checkNum_semester).getSemesterId()+"_"+(checkNum_week+1));
                intent.putExtras(bundle);
                SetWeekActivity.this.setResult(2,intent);
                finish();
            }
        });
        submitBtn = findViewById(R.id.submit_btn);
        submitBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                /*if (!userName.equals("")&&userName!=null)
                    setConditionsByPost();*/
                //返回数据
                if (semesters!=null){
                    Intent intent=new Intent();
                    Bundle bundle=new Bundle();
                    bundle.putString("weekid", semesters.get(checkNum_semester).getSemesterId()+"_"+(checkNum_week+1));
                    intent.putExtras(bundle);
                    SetWeekActivity.this.setResult(2,intent);
                }
                finish();
            }
        });

    }

    private void updateStatus(View v, String userName) {
    }

    private void initView() {
        semesterIG = (ItemGroup) findViewById(R.id.select_semester_ig);
        weekIG = (ItemGroup) findViewById(R.id.select_week_ig);
        semesterIG.setItemOnClickListener(this);
        weekIG.setItemOnClickListener(this);
    }

    @Override
    public void onItemClick(View v) {
        switch (v.getId()) {
            case R.id.select_semester_ig:
                String title3 = "选择学期";
                showSingleAlertDialogNoBtn(v, semesterItems, title3, 1);
                break;
            case R.id.select_week_ig:
                String title4 = "选择周次";
                showSingleAlertDialogNoBtn(v, weekItems, title4, 2);
                break;
        }
    }

    private AlertDialog singleAlertDialogNoBtn;

    public void showSingleAlertDialogNoBtn(View view, final String[] items, String title, final int thisCheckNumClassify) {

        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
        alertBuilder.setTitle(title);
        switch (thisCheckNumClassify) {
            case 1:
                checkNum = checkNum_semester;
                break;
            case 2:
                checkNum = checkNum_week;
                break;
        }

        alertBuilder.setSingleChoiceItems(items, checkNum, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int index) {
                Toast.makeText(SetWeekActivity.this, items[index], Toast.LENGTH_SHORT).show();
                checkNum = index;
                switch (thisCheckNumClassify) {
                    case 1:
                        checkNum = index;
                        checkNum_semester = index;
                        semesterIG.setText(items[index]);
                        changeWeekItems(index);
                        break;
                    case 2:
                        checkNum = index;
                        checkNum_week = index;
                        weekIG.setText(items[index]);
                        break;
                }
                singleAlertDialogNoBtn.dismiss();
            }
        });
        singleAlertDialogNoBtn = alertBuilder.create();
        singleAlertDialogNoBtn.show();
    }

    //更新周数
    private void changeWeekItems(int index) {

        if (semesters!=null){
            int weekQuantity = semesters.get(index).getWeekQuantity();
            weekItems = new String[weekQuantity];
            for (int j = 0; j < weekQuantity; j++) {
                int tempWeekNum = j + 1;
                weekItems[j] = "第" + tempWeekNum + "周";
            }
            checkNum_week = 0;
        }
    }

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SHOW_RESPONSE:
                    String response = (String) msg.obj;          // 在这里进行UI操作，将结果显示到界面上
                    //responseText.setText(response);
            }
        }
    };

    /*获取数据*/
    private void findSemestersByGET() {
        //开启线程来发起网络请求
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                try {
                    URL url = new URL(findUrl);
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    connection.setDoInput(true);
                    //connection.setDoOutput(true);
                    InputStream in = connection.getInputStream();                    // 下面对获取到的输入流进行读取
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    Message message = new Message();
                    message.what = SHOW_RESPONSE;                    // 将服务器返回的结果存放到Message中
                    message.obj = response.toString();
                    handler.sendMessage(message);

                    final String resp = response.toString();
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            parseJSON (resp);
                        }
                    });


                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }).start();

    }

    private void parseJSON(String jsonData) {
        try {
            JSONObject jsonObj = new JSONObject(jsonData);
            semesterJson = jsonObj.getJSONArray("semesters");
            semesters = new ArrayList<>();
            semesterItems = new String[semesterJson.length()];
            for (int i = 0; i < semesterJson.length(); i++) {
                JSONObject jsonObjectTemp = semesterJson.getJSONObject(i);
                semesterItems[i] = jsonObjectTemp.getString("semesterName");
                Semester semester = new Semester();
                semester.setSemesterId(jsonObjectTemp.getString("semesterId"));
                semester.setSemesterName(jsonObjectTemp.getString("semesterName"));
                semester.setWeekQuantity(jsonObjectTemp.getInt("weekQuantity"));
                semesters.add(semester);
            }
            for (int i = 0; i < semesterItems.length; i++) {
                if (checkSemester.equals(semesterItems[i])) {
                    semesterIG.setText(checkSemester);
                    checkNum_semester = i;
                    int allweekNum = semesterJson.getJSONObject(i).getInt("weekQuantity");
                    weekItems = new String[allweekNum];
                    for (int j = 0; j < allweekNum; j++) {
                        int tempWeekNum = j + 1;
                        weekItems[j] = "第" + tempWeekNum + "周";
                    }
                    weekIG.setText(weekItems[checkNum_week]);
                    break;
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
